from tools.tw import jl, ini, itw
import tools.config as cfg
from tools.database import SQLite
from datetime import datetime

def update_database(db_manager, id_value, size, active_line_grade, enabled, ip, treepath, line):
    """更新数据库中的分档信息"""
    # 如果未启用，则设置为"分档未更新"
    if not enabled:
        update_query = f"UPDATE ip_config SET current_segment = '分档未更新' WHERE id = {id_value}"
        db_manager.execute_query(update_query)
        return "分档未更新"  # 返回更新后的值

    new_grade = None
    if size == "S7":
        # 处理S7类型的分档
        xml_filename = ini.get_xml_data(treepath, r"//FileName/text()")
        if xml_filename:
            new_grade = xml_filename[0]
    elif size == "S7-TPE":
        # 处理S7-TPE类型的分档
        ini_filename = ini.read_ini_key(ini_path=treepath, section='Classification', key='CurrentClassification')
        if ini_filename:
            new_grade = ini_filename

    # 如果获取到新的分档且与当前分档不同，则更新数据库
    if new_grade and new_grade != active_line_grade:
        update_query = f"UPDATE ip_config SET current_segment = '{new_grade}' WHERE id = {id_value}"
        db_manager.execute_query(update_query)
        return new_grade  # 返回更新后的值
    return active_line_grade  # 返回原有的值

def main():
    """主函数"""
    # 初始化数据库连接
    db_manager = SQLite(cfg.dbpath)
    if not db_manager.connect():
        print("数据库连接失败")
        return

    try:
        # 获取数据
        var = jl.get_value()
        var_ip = jl.get_ip()
        URL = var.get('webhook', '')
        
        changes = []  # 记录变更信息
        
        # 处理每一行数据
        for i in range(len(var_ip)):
            print(f"正在处理第 {i} 行...")
            
            # 获取当前行的数据
            id_value = var_ip["id"][i]
            workshop = var_ip["workshop"][i]
            line = var_ip["line"][i]
            ip = var_ip["ip"][i]
            segment_path = var_ip["segment_path"][i]
            is_enabled = var_ip["is_enabled"][i]
            active_line_grade = var_ip["current_segment"][i]
            access_path = f"\\\\{ip}{segment_path}"
            
            # 更新数据库并检查是否有变更
            new_grade = update_database(db_manager, id_value, workshop, active_line_grade, is_enabled, ip, access_path, line)
            
            # 检查是否有变更（比较返回的新值与原来的值）
            if new_grade != active_line_grade:
                # 记录变更信息
                change_info = {
                    'id': id_value,
                    'ip': ip,
                    'size': workshop,
                    'line': line,
                    'old_grade': active_line_grade,
                    'new_grade': new_grade,  # 使用函数返回的新值
                    'change_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                }
                changes.append(change_info)
                print(f"分档变化记录: {change_info}")

        # 如果有变更，发送通知
        if changes and URL:
            summary = f"【分档变更】共 {len(changes)} 条变化:\n时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
            for change in changes:
                summary += f" 线别: {change['size']}-{change['line']}>>>旧分档: {change['old_grade']}, 新分档: {change['new_grade']};\n"
            
            itw.send_message(URL, summary)
            print("分档变化信息已发送到I通威")
        else:
            print("没有检测到分档变化")

    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        db_manager.close()

if __name__ == "__main__":
    main()